$(function(){ 
	$('#mainUI .list-content-div table thead tr th:last').attr("width","10%");
	initMap();
});

//创建地图
function initMap(){
	var map = new google.maps.Map(document.getElementById('allmap'), {
	//始终给一个默认地图中心防止任何可能出现的错误结果
	center: {lat: 31.2303904000, lng: 121.4737021000},
	zoom: 8,
	zoomControl: true,
	mapTypeControl: true,
	scaleControl: true,
	streetViewControl: false,
	rotateControl: false,
	fullscreenControl: false
    });
	var geoc=new google.maps.Geocoder();
	var infoWindow = new google.maps.InfoWindow;
    window.map = map;//将map变量存储在全局
    window.geoc = geoc;//将geoc变量存储在全局
    window.iw = infoWindow;//将infoWindow变量存储在全局
    var markers = [];
    window.markers = markers;//将markers数组存储在全局
    
    map.addListener('click', function (event) {
    	var lat=event.latLng.lat();
    	var lng=event.latLng.lng();
        var latlng = {lat: parseFloat(lat), lng: parseFloat(lng)};
        geoc.geocode({'location': latlng}, function(results, status) {
	        if (status === 'OK') {
	          if (results[0]) {
	        	  document.getElementById("longitude").value = lng;
	           	  document.getElementById("latitude").value = lat;
	           	  document.getElementById("position_name").value =results[0].formatted_address;
	          } else {
	        	  document.getElementById("longitude").value = "";
	           	  document.getElementById("latitude").value = "";
	           	  document.getElementById("position_name").value = "未知地点,请重新选择";
	          }
	        } else {
	        	document.getElementById("position_name").value ="目标地点有误,请重新选择,错误信息为 :Geocoder failed due to "+status;
	            document.getElementById("longitude").value = "";
	         	document.getElementById("latitude").value = "";
	        }
	      });
    });
}
//创建marker
function addMarker(location,res) {
  var marker = new google.maps.Marker({
      position: location,
      map: map
    });
	marker.addListener('click', function() {
	    map.setZoom(8);
	    map.setCenter(marker.getPosition());
	    if(res!=null){
	    	iw.setContent("<p>"+res.formatted_address+"</p>");
            iw.open(map,marker);
            document.getElementById("longitude").value = marker.getPosition().lng();
         	document.getElementById("latitude").value = marker.getPosition().lat();
         	document.getElementById("position_name").value =res.formatted_address;
	    }
	});
    markers.push(marker);
}
//marker操作>>>
//marker添加
function setMapOnAll(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}
//marker隐藏
function clearMarkers() {
  setMapOnAll(null);
}
//marker显示
function showMarkers() {
  setMapOnAll(map);
}
//marker删除
function deleteMarkers() {
  clearMarkers();
  markers = [];
}


//用经纬度设置地图中心点
function theLocation(){
	iw.close(map);
	if(document.getElementById("longitude").value != ""||document.getElementById("longitude").value != null && document.getElementById("latitude").value != ""||document.getElementById("latitude").value != null){
		 var latlng = {lat: parseFloat(document.getElementById("latitude").value), lng: parseFloat(document.getElementById("longitude").value)};
		 deleteMarkers();
		 geoc.geocode({'location': latlng}, function(results, status) {
		        if (status === 'OK') {
		          if (results[0]) {
		        	  addMarker(latlng,results[0]);
		        	  map.setZoom(8);
		        	  map.setCenter(latlng);
		        	  document.getElementById("CurrentLocation").innerText = "当前定位: "+results[0].formatted_address;
		          } else {
		        	  document.getElementById("CurrentLocation").innerText = "当前定位: No results found";
		          }
		        } else {
		   	    	document.getElementById("CurrentLocation").innerText ="当前位置定位失败,错误信息为: Geocoder failed due to: " + status;
		        }
		      });
	}
}

//搜索
$('#searchKeyword').on('keydown',function(event){  
    if(event.keyCode == "13"){  
       $("#mapsearch").click();
    }  
});
$("#mapsearch").click(function() { 
	 geocodeAddress(geoc, map);
});

//搜索
function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('searchKeyword').value;
    geocoder.geocode({'address': address}, function(results, status) {
      if (status === 'OK') {
          resultsMap.setCenter(results[0].geometry.location);
          deleteMarkers();
          for (var i=0;i<results.length;i++){
        	  addMarker(results[i].geometry.location,results[i]);
          }
      } else {
    	document.getElementById("CurrentLocation").innerText = "搜索失败,错误信息为: "+status;
      }
    });
}

//当前位置定位
function Positioning(){
	 iw.close(map);
	 if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(function(position) {
           var pos = {
             lat: position.coords.latitude,
             lng: position.coords.longitude
           };
           iw.setPosition(pos);
           iw.setContent('您可能在这里');
           iw.open(map);
           map.setCenter(pos);
           geoc.geocode({'location': pos}, function(results, status) {
   	        if (status === 'OK') {
   	          if (results[0]) {
   	        	  document.getElementById("CurrentLocation").innerText = "当前定位: "+results[0].formatted_address;
   	          } else {
   	        	  document.getElementById("CurrentLocation").innerText = "当前定位: No results found ";
   	          }
   	        } else {
   	        	document.getElementById("CurrentLocation").innerText ="当前位置定位失败,错误信息为:Geocoder failed due to: "+status;
   	        }
   	      });
         }, function() {
           handleLocationError(true, map.getCenter());
         });
       } else {
         // Browser doesn't support Geolocation
         handleLocationError(false, map.getCenter());
       }
     }

     function handleLocationError(browserHasGeolocation, pos) {
    	   document.getElementById("CurrentLocation").innerText=
    		     "当前位置定位失败! "+browserHasGeolocation ?
                 'Error: The Geolocation service failed.' :
                 'Error: Your browser doesn\'t support geolocation.';
     }


	//关闭位置对话框
	$('.MapModalClose').on('click', function() { 
	    $('#PositionMapModal').modal('hide');
	});

	 //新增窗口打开
	 $('.row>.col-xs-1>a').on('click', function() {
		document.getElementById("CurrentLocation").innerText = "当前定位: 正在定位中...";
		$(".MapModalAddDetermine").removeClass('hidden');
		$(".MapModalEditDetermine").addClass('hidden');
		$("#PositionForm :input").val('');
		//编码接口
		$.post($('body').attr('ctxPath')+'/position/generateCode?t='+new Date().getTime(),function(data){
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes(),
			treeNode = nodes[0];
			if(!data.flag){
				layer.alert(data.msg);
				return;
			}else{
				$('#position_code').val(data.msg);
			}
			$('#position_name').val("");
			$('#position_desc').val("");
			if(treeNode==null){
		 		$('#long_code').val(data.msg);
		 	}else{
		 		$('#region_number').val(treeNode.regionCode);
		 		$('#long_code').val(treeNode.longCode+"!"+data.msg);
		 	}
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
		 	nodes = zTree.getSelectedNodes(),
		 	treeNode = nodes[0];
		 	if (nodes.length == 0) {
		 		layer.open({
		 			  title: '消息提示',
		 			  offset: '200px'
		 			  ,content:"请选择区域！"
		 			});     
		 			$('body').scrollTop(100);
		 		return;
		 	}
		$('#PositionMapModal').modal({
		 	moveable:false,
		 	show: true
		 });
		//ip定位
		Positioning();
		});
	 });
	 
	    //新增位置保存
		$(".MapModalAddDetermine").on('click',function(){
			$("#PositionId").val('');
			 $.post($('body').attr('ctxPath') +'/position/addPosit?t='+new Date().getTime(),$('#PositionForm').serialize(),function(data){
				 if(data.state){
					 $('#PositionMapModal').modal('hide');
					 listui.refresh("mainUI");
					 layer.open({
			 				  title: '消息提示',
			 				  offset: '200px',
			 				  content: data.msg
			 				});
			 				$('body').scrollTop(100);
					}else if(data.state!=null){
						layer.open({
			 				  title: '消息提示',
			 				  offset: '200px',
			 				  content:data.msg
			 				});
			 				$('body').scrollTop(100);
					}else{
						layer.open({
			 				  title: '消息提示',
			 				  offset: '200px',
			 				  content:"添加失败!"
			 				});
			 				$('body').scrollTop(100);
					}
		});
	});
		
	 //编辑位置保存
	 $(".MapModalEditDetermine").on('click',function(){
		 $.post($('body').attr('ctxPath') +'/position/editPosit?t='+new Date().getTime(),$('#PositionForm').serialize(),function(data){
			 if(data.state){
				 $('#PositionMapModal').modal('hide');
				 listui.refresh('mainUI');
				 layer.open({
		 				  title: '消息提示',
		 				  offset: '200px',
		 				  content: data.msg
		 				});
		 				$('body').scrollTop(100);
				}else if(data.state!=null){
					layer.open({
		 				  title: '消息提示',
		 				  offset: '200px',
		 				  content:data.msg
		 				});
		 				$('body').scrollTop(100);
				}else{
					layer.open({
		 				  title: '消息提示',
		 				  offset: '200px',
		 				  content:"添加失败!"
		 				});
		 				$('body').scrollTop(100);
				}
		 });
	 });

//数据表格搜索参数
function getCustomQueryData() {
	var longCode = $('#long_number').val();
	if (longCode == "") {
		return false;
	}
	return {
		'longCode' : longCode
	}
}
// 数据表格操作按钮
function handleOpRow(tr, obj, container) {
	tr.append($('<td/>').addClass('op').append($('<a/>', {
		"href" : "javascript:;",
		"data-id" : obj.id
	}).addClass('edits').text('编辑')).append($('<span/>').text(' | ')).append($('<a/>', {
		"href" : "javascript:;",
		"data-id" : obj.id
	}).addClass('delete').text('删除')));
}

$('.list-content-div table>tbody').delegate('tr>td>.delete', 'click', function() {
	var id = $(this).attr('data-id');
	$.get($('body').attr('ctxPath')+'/position/checkPosit/'+id+'?t='+new Date().getTime(),function(data){
		if(/*data.state*/ false){
			layer.msg("该位置已被引用，无法删除！");
			}else{
				layer.confirm('确定删除该记录吗？', {
					  btn: ['确认','取消'] //按钮
					}, function(){
				//根据id获取位置信息
				$.get($('body').attr('ctxPath')+'/position/deletePosit/'+id+'?t='+new Date().getTime(),function(data){
						if(data.state){
							 listui.refresh('mainUI');
							layer.open({
				 				  title: '消息提示',
				 				  offset: '200px',
				 				  content: data.msg
				 				});
				 				$('body').scrollTop(100);
						}
					});
				})	
			}
     });
	
	});
//编辑位置打开
$('.list-content-div table>tbody').delegate('tr>td>.edits', 'click', function() {
	$(".MapModalAddDetermine").addClass('hidden');
	$(".MapModalEditDetermine").removeClass('hidden');
	var id = $(this).attr('data-id');
	$.get($('body').attr('ctxPath')+'/position/checkPosit/'+id+'?t='+new Date().getTime(),function(data){
		if(/*data.state  验证是否被引用*/ false){
			layer.msg("该位置已被引用，无法编辑！");
			}else{
				$.get($('body').attr('ctxPath')+'/position/getPosit/'+id+'?t='+new Date().getTime(),function(data){
						if(data.state){
							document.getElementById("CurrentLocation").innerText = "当前定位: 正在定位中...";
							var posit=data.obj//obj：BtPositionInfo对象
							for(var item in posit){
		                            var name = item,val = posit[item];
		                            $('#PositionForm :input[name=' + name + ']').val(val);
							}
							$('#PositionMapModal').modal({
							 	moveable:false,
							 	show: true
							 });
							//根据目标经纬度定位
							theLocation();
						}else{
							layer.open({
				 				  title: '消息提示',
				 				  offset: '200px',
				 				  content:"获取数据失败!"
				 				});
				 				$('body').scrollTop(100);
						}
					});
			}
	});
	});

